#include <utils.h>
#include <Windows.h>

//wstring=>string
std::string WString2String(const std::wstring& ws)
{
    std::string strLocale = setlocale(LC_ALL, "");
    const wchar_t* wchSrc = ws.c_str();
    size_t nDestSize = wcstombs(NULL, wchSrc, 0) + 1;
    char *chDest = new char[nDestSize];
    memset(chDest, 0, nDestSize);
    wcstombs(chDest, wchSrc, nDestSize);
    std::string strResult = chDest;
    delete[]chDest;
    setlocale(LC_ALL, strLocale.c_str());
    return strResult;
}
// string => wstring
std::wstring String2WString(const std::string& s)
{
    std::string strLocale = setlocale(LC_ALL, "");
    const char* chSrc = s.c_str();
    size_t nDestSize = mbstowcs(NULL, chSrc, 0) + 1;
    wchar_t* wchDest = new wchar_t[nDestSize];
    wmemset(wchDest, 0, nDestSize);
    mbstowcs(wchDest, chSrc, nDestSize);
    std::wstring wstrResult = wchDest;
    delete[]wchDest;
    setlocale(LC_ALL, strLocale.c_str());
    return wstrResult;
}

void EndianSwap(uint8_t *pData, int startIndex, int length)
{
    int i,cnt,end,start;
    cnt = length / 2;
    start = startIndex;
    end  = startIndex + length - 1;
    uint8_t tmp;
    for (i = 0; i < cnt; i++)
    {
        tmp            = pData[start+i];
        pData[start+i] = pData[end-i];
        pData[end-i]   = tmp;
    }
}

vector<wstring> SplitStrW(wstring Text, wstring site) {
	vector<wstring> resultVec;

	wchar_t* c_str = new wchar_t[Text.size()*2];
	memset(c_str, 0, (Text.size()+1) * 2);
	memcpy(c_str, &Text[0], Text.size() * 2);

	wchar_t* c_str2 = new wchar_t[site.size()*2];
	memset(c_str2, 0, (site.size()+1) * 2);
	memcpy(c_str2, &site[0], site.size() * 2);

	wchar_t* c_str3 = wcstok(c_str, c_str2);
	while (c_str3 != NULL)
	{
		resultVec.push_back(wstring(c_str3));
		c_str3 = wcstok(NULL, c_str2);
	}
	return resultVec;
}

wstring dirnameOf(const std::wstring& fname)
{
     size_t pos = fname.find_last_of(L"\\/");
     return (std::wstring::npos == pos)
         ? L""
         : fname.substr(0, pos);
}

wstring fnameOf(const std::wstring& fname)
{
    size_t pos = fname.find_last_of(L"\\/");
    size_t endpos = fname.find_last_of(L".");
    return fname.substr(pos+1, endpos-pos-1);
}

wstring suffixOf(const std::wstring& fname)
{
    return fname.substr(fname.find_last_of(L".") + 1);
}

void char_to_wchar(const char* ch, std::wstring& w_str)
{
    wchar_t* wchar;
    int len = MultiByteToWideChar(CP_ACP, 0, ch, strlen(ch), NULL, 0);
    wchar = new wchar_t[len + 1];
    MultiByteToWideChar(CP_ACP, 0, ch, strlen(ch), wchar, len);
    wchar[len] = '\0';
    w_str = wchar;
    delete[]wchar;
}
